<!--字典类别-->
<script setup lang="ts">
import {
  getDictTypePage,
  addDictType,
  deleteDictTypes,
  getDictOptions,
} from "@/api/dict";

import { DictTypePageVO, DictTypeQuery, DictTypeForm } from "@/api/dict/types";
import { filterOrder } from "@/utils/commonHooks";

defineOptions({
  name: "SYSTEMDICT",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const queryTotal = ref(0);

const queryParams = reactive<DictTypeQuery>({
  current: 1,
  size: 10,
  data: {
    code: "",
    dictionaryName: "",
  },
  sort: {
    column: "code",
    orderBy: "asc",
  },
});

const dictTypeList = ref<DictTypePageVO[]>();

const dictionarys: Ref<OptionType[]> = ref([]); // 字典下拉数据源

const dialog = reactive<DialogOption>({
  visible: false,
});

const formData = reactive<DictTypeForm>({
  code: "",
  dictionaryName: "",
  sort: 0,
  enabled: 1,
  remarks: "",
});

const rules = reactive({
  code: [
    { required: true, message: "请输入字典类别编码", trigger: "blur" },
    { max: 45, message: "字典类别编码不能超过45个字符", trigger: "blur" },
  ],
  dictionaryName: [
    { required: true, message: "请选择字典类别名称", trigger: "blur" },
    { max: 45, message: "字典类别名称不能超过45个字符", trigger: "blur" },
  ],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getDictTypePage(queryParams)
    .then((res: any) => {
      const { total, data } = res;
      dictTypeList.value = data;
      queryTotal.value = total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.current = 1;
  queryParams.data.code = "";
  queryParams.data.dictionaryName = "";
  handleQuery();
}

/** 行复选框选中  */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

// 监听表格后台排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  queryParams.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };

  handleQuery();
}

/**
 * 打开字典类别表单弹窗
 *
 * @param dicTypeId 字典类别ID
 */
function openDialog(data?: any) {
  dialog.visible = true;
  if (data?.id) {
    dialog.title = "修改字典类别";
    const { enabled, code, dictionaryName, sort, remarks, id } = data;
    Object.assign(formData, {
      enabled,
      code,
      sort: sort || 0,
      dictionaryName,
      remarks,
      id,
    });
  } else {
    delete formData.id;
    dialog.title = "新增字典类别";
  }
}

/** 字典类别表单提交 */
function handleSubmit() {
  dataFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      loading.value = true;
      addDictType(formData)
        .then(() => {
          ElMessage.success("新增成功");
          closeDialog();
          handleQuery();
        })
        .finally(() => (loading.value = false));
    }
  });
}

/** 关闭字典类别弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/**  重置字典类别表单 */
function resetForm() {
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  formData.code = "";
  formData.dictionaryName = "";
  formData.sort = 0;
  formData.enabled = 1;
  formData.remarks = "";
}

/** 删除字典类别 */
const deleteLoading = ref(false);
function handleDelete(dictTypeId?: number) {
  const dictTypeIds = [dictTypeId || ids.value].join(",");
  if (!dictTypeIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    const dictIdsArr = dictTypeIds.split(",");
    const data = {
      ids: dictIdsArr,
    };
    deleteLoading.value = true;
    deleteDictTypes(data)
      .then(() => {
        ElMessage.success("删除成功");
        handleQuery();
      })
      .catch(() => ElMessage.info("已取消删除"))
      .finally(() => {
        deleteLoading.value = false;
      });
  });
}

const dictDataDialog = reactive<DialogOption>({
  visible: false,
});

let selectedDictType = reactive<DictTypePageVO>({
  typeCode: "",
  typeName: "",
  id: "",
}); // 当前选中的字典类别

/** 打开字典数据弹窗 */
function openDictDialog(row: DictTypePageVO) {
  dictDataDialog.visible = true;
  dictDataDialog.title = "【" + row.dictionaryName + "】字典数据";

  selectedDictType = {
    id: row.id,
    typeCode: row.code,
    typeName: row.dictionaryName,
  };
}

/**  关闭字典数据弹窗 */
function closeDictDialog() {
  dictDataDialog.visible = false;
}

onBeforeMount(() => {
  // 根据字典类别编码(typeCode)获取字典选项
  getDictOptions({}).then((response) => {
    dictionarys.value = response.data;
  });
});

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="字典类别">
          <el-input
            v-model="queryParams.data.dictionaryName"
            placeholder="请选择字典类别名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="字典编码">
          <el-input
            v-model="queryParams.data.code"
            placeholder="字典类别编码"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery()"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetQuery()"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          plain
          :loading="deleteLoading"
          @click="handleDelete()"
          ><i-ep-delete />删除</el-button
        >
      </template>
      <el-table
        v-loading="loading"
        highlight-current-row
        :data="dictTypeList"
        border
        @selection-change="handleSelectionChange"
        @sort-change="onTableSortChanged"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="字典类别名称"
          prop="dictionaryName"
          width="200"
          show-overflow-tooltip
        />
        <el-table-column sortable="custom" label="排序" prop="sort" />
        <el-table-column
          label="字典类别编码"
          prop="code"
          show-overflow-tooltip
        />
        <el-table-column label="是否启用" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.enabled === 1" type="success">启用</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remarks" show-overflow-tooltip />
        <el-table-column fixed="right" label="操作" align="center" width="240">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="small"
              @click.stop="openDictDialog(scope.row)"
              ><i-ep-Collection />字典数据</el-button
            >
            <el-button
              type="primary"
              link
              size="small"
              @click.stop="openDialog(scope.row)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              type="primary"
              link
              size="small"
              @click.stop="handleDelete(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="queryTotal > 0"
        v-model:total="queryTotal"
        v-model:page="queryParams.current"
        v-model:limit="queryParams.size"
        @pagination="handleQuery"
      />
    </el-card>

    <el-dialog
      :close-on-click-modal="false"
      v-model="dialog.visible"
      draggable
      :title="dialog.title"
      width="650px"
      @close="closeDialog"
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="字典类别" prop="dictionaryName">
              <el-input
                v-model="formData.dictionaryName"
                placeholder="请输入字典类别"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="字典编码" prop="code">
              <el-input v-model="formData.code" placeholder="请输入字典编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number autocomplete="off" v-model="formData.sort" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="是否启用" prop="enabled">
          <el-radio-group v-model="formData.enabled">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="formData.remarks"
            type="textarea"
            placeholder="请输入字典类别备注"
            show-word-limit
            :maxlength="250"
            :autosize="{ minRows: 3, maxRows: 4 }"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--字典数据弹窗-->
    <el-dialog
      :close-on-click-modal="false"
      draggable
      v-model="dictDataDialog.visible"
      :title="dictDataDialog.title"
      class="pt10_self"
      width="1000px"
      @close="closeDictDialog"
    >
      <dict-item
        v-model:typeCode="selectedDictType.typeCode"
        v-model:typeName="selectedDictType.typeName"
        v-model:id="selectedDictType.id"
      />
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
:deep(.pt10_self .el-dialog__body) {
  max-height: 600px;
  overflow-y: auto;
}
</style>
<style lang="scss" scoped>
:deep(.el-form .el-form-item__label) {
  width: 63px;
}
</style>
